//
//  JXUserViewModel.swift
//  swift高仿微博
//
//  Created by peijiaxing on 16/2/26.
//  Copyright © 2016年 peijiaxing. All rights reserved.
//

import UIKit
import AFNetworking

//通过code来换取Token
class JXUserViewModel: NSObject {

    // 定义一个单例
    static let shareInstance = JXUserViewModel()
    
    // 定义属性
    var model: JXUserModel?
    
    // token
    var access_token: String?{
        return model?.access_token
    }
    // 是否登录
    var isLogin:Bool? {
        return model?.access_token != nil ? true: false
//        print(model)
    }
    
    private override init() {
        model = JXUserModel.loadUserModel("rues.pdf")
    }
    
    // 定义一个请求Token的方法
     func loadToken(code:String,success: ()->(),failure: ()->()){
        // 写一个网络请求
            // 创建一个管理者
        let afn = AFHTTPSessionManager()
        
            // 修改 afn 类型 
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        // 定义参数
        let params = ["client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":AppRedirectUri]
//        print(params)
        
        // 发送请求
        afn.POST("https://api.weibo.com/oauth2/access_token", parameters: params, progress: nil , success: { (_ , JSON) -> Void in
            
            print(JSON)
            
            if let Odic = JSON as? [String:NSObject]{
                
                self.model = JXUserModel(dic: Odic)
                
                self.getPersonInfo(self.model!, success: success, failure: failure)
                
            }
            
            }) { (_ , error) -> Void in
                
//                print(error)
                
                failure()
        }
    }
      ///MARK:--通过Toekn来获取用户信息
    func getPersonInfo(userModel: JXUserModel,success: () -> (),failure: () -> ()){
        
        
        // 创建一个网络请求
        let afn = AFHTTPSessionManager()
        // 参数
        let params = [
            "access_token":userModel.access_token ?? "",
            "uid":userModel.uid ?? ""]
        
        print(params)
        
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: params, progress:nil,success: { (_ , JSON) -> Void in
            
            
            if let dic = JSON as? [String:NSObject] {
                
                // 设置头像与名字
                userModel.profile_image_url = dic["profile_image_url"] as? String
                userModel.screen_name = dic["screen_name"] as? String
                
                // 保存到沙盒里 userModel.save("保存文件名")
                userModel.save("rues.pdf")
                
                
                success()
            }
            
            }) { (_ , error) -> Void in
                print(error)
                failure()
        }
        
        
    }
    
}
